import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken, TOKEN_KEY } from '@/ts/auth'

const BASE_URL = ''

// 创建axios实例
const service = axios.create({
  baseURL: BASE_URL, // api 的 base_url
  timeout: 20000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config: any) => {
    config.headers[TOKEN_KEY] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    return config
  },
  (error: any) => {
    ElMessage.error(error.message)
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  (response: any) => {
    const res = response.data
    // debugger
    if (res.code !== 200) {
      ElMessage.error(res.message)
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  (error: any) => {
    console.log('err' + error) // for debug
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)

export default service
